import { createRouter, createWebHashHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import { useAnimateStore } from '../stores/animate';
import { RouterItem } from './modules/index';
import { useUserStore } from '../stores/user';


const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: "/dashboard",
    name: "dashboard",
    component: () => import("../views/dashboard/index.vue"),
    children: RouterItem,
    redirect: '/dashboard/home'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  },
  {
    path: "/:pathMatch(.*)",
    component: () => import("../views/404/index.vue")
  }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

//使用路由拦截进行动画切换
let timer: any = null;
let timermon: any = null;
router.beforeEach((to, from, next) => {

  const userStore = useUserStore();
  let token = userStore.token;

  const animatestore = useAnimateStore && useAnimateStore();
  animatestore && animatestore.SetAnimate(false);
  timer && clearTimeout(timer);
  timermon && clearTimeout(timermon);
  timer = setTimeout(async () => {
    console.log(to, 'to12');

    //token 存在 
    if (to.path != '/login' && !token) {
      next({
        path: '/login'
      })
    } else {
      if (to.path == '/login' && token) {
        next("/dashboard")
      }
      else {
        next()
      }
    }


    timermon = setTimeout(async () => {
      if (!userStore.user.id && token) {
        await userStore.getUserInfoAction();
      }
      animatestore && animatestore.SetAnimate(true);
    }, 500);

  }, 200);
});

router.afterEach((to, from) => {
  if (to.meta.title) {
    document.title = to.meta.title as string
  }
  else {
    document.title = 'AIOT'
  }
})
export default router
